import { store } from "../../store/index";
import { login, getReceiverBalance, getReceiverAnalyse } from "../api/index";

Page({
  data: {
    userInfo: null,
    table: 0,
    inviteCode: "",
    receiverAnalyse: {
      balance: 0,
      today: 0,
      month: 0,
      total: 0,
    },
    templateIds: {
      userMessage: "6NBPto5OTxzggUX0V6lKypAjPjaMXIyvFT0tyVher38",
      orderReminder: "CHLU78fhz-TODgK_nB10F8Ss-826tjOZuXLpq602Wlg",
    },
    isOpen: false,
  },

  onLoad(options) {
    console.log(options, "options");
    // wx.setStorageSync('inviteCode', options.inviteCode);
    if (options?.inviteCode) {
      this.setData({
        inviteCode: options.inviteCode,
      });
    }
  },

  onShow() {
    this.setData({
      table: store.activeTable,
    });
    if (wx.getStorageSync("openId")) {
      store.getUserInfo().then((res) => {
        this.setData({
          userInfo: res,
        });
        if (res.applyStatus === "通过") {
          this.getReceiverBalance();
          this.getReceiverAnalyse();
        }
      });
    }
    this.checkSubscriptionStatus();
  },
  getReceiverBalance() {
    getReceiverBalance().then((res) => {
      this.setData({
        receiverAnalyse: {
          ...this.data.receiverAnalyse,
          balance: res.result,
        },
      });
    });
  },
  getReceiverAnalyse() {
    getReceiverAnalyse().then((res) => {
      this.setData({
        receiverAnalyse: {
          ...this.data.receiverAnalyse,
          today: res.result.oneDay,
          month: res.result.oneMonth,
          total: res.result.total,
        },
      });
    });
  },

  handleLogin() {
    wx.login({
      success: (res) => {

        if (res.code) {
          // 发起网络请求
          wx.getUserInfo({
            success: async (userInfoRes) => {
              this.setData({
                userInfo: userInfoRes.userInfo,
              });
              login({
                code: res.code,
                nickName: userInfoRes.userInfo.nickName,
                avatarUrl: userInfoRes.userInfo.avatarUrl,
                inviteCode: this.data.inviteCode || "",
              }).then((res) => {
                wx.setStorageSync("openId", res.result);
                store.getUserInfo().then((res) => {
                  console.log("getUserInfo success:", res);
                  this.setData({
                    userInfo: res,
                  });
                });
              });
            },
            fail: (err) => {
              console.error("Failed to get user info:", err);
            },
          });
        } else {
          console.log("Login failed:", res.errMsg);
        }
      },
      fail: (err) => {
        console.error("wx.login failed:", err);
      },
    });
  },
  handleEdit() {
    wx.navigateTo({
      url: "/pages/me/userEdit/index",
    });
  },

  goTo(e) {
    console.log(e);
    if (
      e.currentTarget.dataset.page === "me_content/aplay" &&
      this.data.userInfo?.applyStatus === "申请中"
    ) {
      wx.showToast({
        title: "您正在申请接单员，请耐心等待审核",
        icon: "none",
      });
      return;
    }
    wx.navigateTo({
      url: `/pages/${e.currentTarget.dataset.page}`,
    });
  },
  checkUser() {
    store.updateActiveTable(store.activeTable === 0 ? 1 : 0);
    this.setData({
      table: store.activeTable,
    });
  },
  telService() {
    wx.makePhoneCall({
      phoneNumber: "18516888888",
    });
  },
  handleSwitchChange(e) {
    if (e.detail) {
      this.toSetting();
    } else {
      wx.showModal({
        title: "取消订阅",
        content: "关闭后将不再接受收到订单状态更新提醒。",
        confirmText: "确认",
        cancelText: "取消",
        success: (res) => {
          if (res.confirm) {
            wx.openSetting({
              withSubscriptions: true,
              success: (res) => {
                this.checkSubscriptionStatus();
              },
            });
          }
        },
      });
    }
  },
  toSetting() {
    if (!wx.getStorageSync("openId")) {
      wx.showToast({
        title: "请先登录",
        icon: "none",
      });
      return;
    }

    // 根据 table 选择对应的标题和内容
    const modalText =
      this.data.table === 0
        ? { title: "开启用户提醒", content: "开启后，您将收到订单状态变更提醒" }
        : { title: "开启接单提醒", content: "开启后，您将收到新订单提醒" };

    wx.showModal({
      title: modalText.title,
      content: modalText.content,
      confirmText: "开启",
      cancelText: "取消",
      success: (res) => {
        if (res.confirm) {
          // 根据角色选择对应的模板ID
          const tmplId =
            this.data.table === 0
              ? this.data.templateIds.userMessage // 用户消息模板
              : this.data.templateIds.orderReminder; // 接单员消息模板

          wx.requestSubscribeMessage({
            tmplIds: [tmplId],
            success: (res) => {
              console.log(res, "res");
              if (res[tmplId] === "accept") {
                wx.showToast({
                  title: "订阅成功",
                  icon: "success",
                });
              } else {
                wx.showModal({
                  title: '订阅失败',
                  content: '请在设置中手动开启',
                  confirmText: '去设置',
                  cancelText: '取消',
                  success: (res) => {
                    if (res.confirm) {
                      wx.openSetting({
                        withSubscriptions: true,
                        success: (res) => {
                          this.checkSubscriptionStatus();
                        }
                      });
                    }
                  }
                });
              }
              this.checkSubscriptionStatus();
            },
            fail: (err) => {
              console.error("订阅失败:", err);
              wx.showModal({
                title: '订阅失败',
                content: '请在设置中手动开启',
                confirmText: '去设置',
                cancelText: '取消',
                success: (res) => {
                  if (res.confirm) {
                    wx.openSetting({
                      withSubscriptions: true,
                      success: (res) => {
                        this.checkSubscriptionStatus();
                      }
                    });
                  }
                }
              });
            },
          });
        }
      },
    });
  },
  checkSubscriptionStatus() {
    wx.getSetting({
      withSubscriptions: true,
      success: (res) => {
        console.log(res, "res");
        if (res.subscriptionsSetting) {
          // 获取对应的模板ID
          const tmplId = this.data.table === 0
            ? this.data.templateIds.userMessage
            : this.data.templateIds.orderReminder;

          // 检查订阅状态
          const isSubscribed = res.subscriptionsSetting.itemSettings 
            && res.subscriptionsSetting.itemSettings[tmplId] === 'accept';

          this.setData({ 
            isOpen: isSubscribed && res.subscriptionsSetting.mainSwitch 
          });
        }
      },
    });
  },
});
